加载中...
java8 Stream 例子
发表于:2021-05-20 | 分类: Stream
字数统计: 450 | 阅读时长: 2分钟 | 阅读量:

数据

1
2
3
4
5
6
List<User> userList = new ArrayList<>();
userList.add(new User(1, "aaa"));
userList.add(new User(2, "bbb"));
userList.add(new User(3, "ccc"));
userList.add(new User(2, "ddd"));
userList.add(new User(3, "eee"));

1. 将id作为map的key,相同的值合并List

1
2
3
4
5
6
7
8
        Map<Integer, List<String>> collect = userList.stream().collect(
Collectors.toMap(User::getId,
// e -> Arrays.asList(e.getUsername()),会报错
e -> CollUtil.newArrayList(e.getUsername()),
(List<String> oldList, List<String> newList) -> {
oldList.addAll(newList);
return oldList;
}));

注意Arrays.asList会报错,除非用new ArrayList<>(Arrays.asList

Collectors.toMap注意:往一个map里put一个已经存在的key,会把原有的key对应的value值覆盖,然而Java8中的Collectors.toMap反其道而行之,它默认给抛异常,抛异常…所以要重写第三个参数

1
Map<Integer, String> collect2 = userList.stream().collect(Collectors.toMap(User::getId, User::getUsername, (oldVal, currVal) -> currVal));

2. 将User的id作为key,Dept中的值取自User,Dept为List作为值

1
2
3
4
5
6
7
Map<Integer, List<Dept>> collect3 = userList.stream().collect(
Collectors.toMap(User::getId,
r -> CollUtil.newArrayList(new Dept(r.getId(), r.getUsername())),
(List<Dept> oldList, List<Dept> newList) -> {
oldList.addAll(newList);
return oldList;
}));

3. 默认groupingBy值为null的话就会报错,重写一个方法

1
2
3
4
        Map<Integer, List<User>> collect4 = userList.stream().collect(
CollectionsUtil.groupingByWithNullKeys(User::getId));
// 默认groupingBy值为null的话就会报错
// Collectors.groupingBy(User::getId));
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static class CollectionsUtil {

/**
* 重写Collectors.groupingBy,允许null key
*/
public static <T, A> Collector<T, ?, Map<A, List<T>>> groupingByWithNullKeys(Function<? super T, ? extends A> classifier) {
return Collectors.toMap(classifier, Collections::singletonList,
(List<T> oldList, List<T> newEl) -> {
List<T> newList = new ArrayList<>(oldList.size() + 1);
newList.addAll(oldList);
newList.addAll(newEl);
return newList;
});
}
}

4. collectingAndThen来转换groupingBy的数据

1
2
3
4
5
6
7
8
9
10
        Map<Integer, User> collect8 = userList.stream().
//对groupingBy的数据过滤null
filter(item -> ObjectUtil.isNotNull(item.getId())).
collect(
// Collectors.groupingBy(User::getId, Collectors
Collectors.groupingBy(User::getId,
Collectors.collectingAndThen(
Collectors.maxBy(
Comparator.comparing(User::getAge)),
Optional::get)));
上一篇:
通用导入
本文目录
本文目录